package com.cqyc.shop.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cqyc.shop.comm.commException;
import com.cqyc.shop.domain.User;
import com.cqyc.shop.services.UserServices;

@WebServlet(urlPatterns="/login.do")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = -7366253802551719145L;
	private Logger logger = LoggerFactory.getLogger(getClass());
	private UserServices userServices = new UserServices();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.debug("开始执行登录方法");
		try {
			//1:从前台获取参数
			String usercode = request.getParameter("usercode");
			String password = request.getParameter("password");
			logger.debug("{}--{}",usercode,password);
			//2:数据转换	
			//3:数据校验
			if(usercode == null || usercode.trim().length()<3 || password==null || password.trim().length()<3) {
				throw new commException("登录账号密码不能为空，并且长度不能小于3");
			}
			logger.debug("校验成功");
			//4:业务调用
		
			User user = userServices.findcode(usercode,password);
			HttpSession session = request.getSession();
			session.setAttribute("user", user);
			logger.debug("{}",user.getUsertype());
			//5:跳转
			response.sendRedirect(request.getContextPath()+"/index.do");
			logger.debug("登录成功");
		} catch (Exception e) {
			logger.error("{}",e.getMessage());
			request.setAttribute("error", e.getMessage());
			request.getRequestDispatcher("/login_f.jsp").forward(request, response);
		}
	}

}
